﻿using CPFrameWork.Global;
using CPFrameWork.UIInterface.Grid;
using CPFrameWork.Utility.DbOper;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;

namespace BusinessManage.ParentsGeneration
{
    public class ParentsGenerationController : CPWebApiBaseController
    {
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();


        #region 列表数据删除

        [HttpGet]
        public CPWebApiBaseReturnEntity DeleteGridData(int CurUserId, string CurUserIden, string GridCode, string DataPks)
        {
            base.SetHeader();
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                CPGrid grid = CPGridEngine.Instance(CurUserId).GetGrid(GridCode, false, false);
                DbHelper dbHelper = new DbHelper(grid.DbIns, CPAppContext.CurDbType());
                StringBuilder sb = new StringBuilder();

                ParentsGeneration parentsGeneration = new ParentsGeneration();


                string[] dataPKValueArray = DataPks.Split('@');
                if (string.IsNullOrEmpty(grid.DelDataSql))
                {
                    string[] pkArray = grid.PKFieldName.Split(',');
                    for (int m = 0; m < dataPKValueArray.Length; m++)
                    {
                       
                        string strSql = "";
                        strSql = "DELETE FROM  " + grid.MainTableName + " WHERE  ";
                        string[] vArray = dataPKValueArray[m].Split(',');
                        for (int i = 0; i < pkArray.Length; i++)
                        {
                            re = parentsGeneration.DeleteYW_OrderDetail(pkArray[i], vArray[i], dbHelper);
                            if (!re.Result) return re;
                            if (i == 0)
                            {
                                strSql += pkArray[i] + "='" + vArray[i] + "';";
                            }
                            else
                            {
                                strSql += " AND " + pkArray[i] + "='" + vArray[i] + "';";
                            }
                        }
                        sb.Append(strSql);
                    }
                }
                else
                {
                    //自己配置了查询条件
                    string strSql = grid.DelDataSql;
                    DataPks = "'" + DataPks.Replace("@", "','") + "'";
                    strSql = strSql.Replace("{@PKValues@}", DataPks);
                    strSql = CPExpressionHelper.Instance.RunCompile(strSql);
                    sb.Append(strSql);
                }
                if (sb.Length > 0)
                {

                    dbHelper.ExecuteNonQuery(sb.ToString());

                }
                re.Result = true;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                re.ErrorMsg = ex.Message.ToString();
                _logger.Error(string.Format("【列表数据删除】参数信息为{0}，异常信息{1}", DataPks, ex));
                return re;
            }
        }
        #endregion

        #region  业务数据删除
        [HttpGet]
        public CPWebApiBaseReturnEntity DeleteBusinessGridData(int CurUserId, string CurUserIden, string GridCode, string OrderIds)
        {
            base.SetHeader();
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                CPGrid grid = CPGridEngine.Instance(CurUserId).GetGrid(GridCode, false, false);
                string[] OrderStr = OrderIds.Split('@');
                foreach (string orderid in OrderStr)
                {
                    DbHelper dbHelper = new DbHelper(grid.DbIns, CPAppContext.CurDbType());
                    
                    using (System.Data.IDbConnection iConn = dbHelper.GetConnection())
                    {
                        using (System.Data.IDbCommand iCmd = iConn.CreateCommand())
                        {
                            // = new System.Data.SqlClient.SqlCommand(Sql, (System.Data.SqlClient.SqlConnection)iConn)
                           
                            iConn.Open();
                            //默认让IDbTransaction对象为空
                            System.Data.IDbTransaction trans = null;
                            //开启事务：标志事务的开始
                            trans = iConn.BeginTransaction();
                            try
                            {

                                iCmd.Transaction = trans;//将事务应用于CMD

                                iCmd.CommandText = "delete  from YW_TaskCarRelation where TaskOrderId in (select Id from  YW_TaskOrderRelation where GivetohallId in (select Id from YW_GivetohallInfo where OrderId in (select ordercode from dbo.YW_OrderInfo where Id=" + orderid + ")) and OrderId in (select ordercode from dbo.YW_OrderInfo where Id=" + orderid + ") );";
                                iCmd.ExecuteNonQuery();

                                iCmd.CommandText = " delete from  YW_TaskOrderRelation where   GivetohallId in (select Id from YW_GivetohallInfo where OrderId  in (select ordercode from dbo.YW_OrderInfo where Id=" + orderid + ") ) and OrderId  in (select ordercode from dbo.YW_OrderInfo where Id=" + orderid + ");";
                                iCmd.ExecuteNonQuery();

                                iCmd.CommandText = "delete from YW_GivetohallInfo where OrderId  in (select ordercode from dbo.YW_OrderInfo where Id=" + orderid + ") ;";
                                iCmd.ExecuteNonQuery();

                                //事务提交
                                trans.Commit();
                                re.Result = true;

                            }
                            catch (System.Exception E)
                            {
                                re.Result = false;
                                //事务回滚
                                trans.Rollback();
                            }
                            finally
                            {
                                if (iConn.State != System.Data.ConnectionState.Closed)
                                {
                                    iConn.Close();
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                re.Result = false;
                re.ErrorMsg = ex.Message.ToString();
                _logger.Error(string.Format("【删除新增订单的业务数据】参数信息为{0}，异常信息{1}", OrderIds, ex));
            }
            return re;
        }
        #endregion

        /// <summary>
        /// 订单数据导入excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public CPWebApiBaseReturnEntity BatchImport([FromBody] ExcelData excelData) {
            base.SetHeader();
            CPWebApiBaseReturnEntity re = new CPWebApiBaseReturnEntity();
            try
            {
                _logger.Info(string.Format("【订单数据导入excel】参数信息为{0}", JsonConvert.SerializeObject(excelData)));
                int CurUserId = excelData.CurUserId;
                string CurUserIden = excelData.CurUserIden;
                string GridCode = excelData.GridCode;
                if (this.CheckUserIden(CurUserId, CurUserIden) == false)
                {
                    re.Result = false;
                    re.ErrorMsg = "登陆超时，请退出重新登陆！";
                    return re;
                }
                CPGrid grid = CPGridEngine.Instance(CurUserId).GetGrid(GridCode, false, false);
                DbHelper dbHelper = new DbHelper(grid.DbIns, CPAppContext.CurDbType());
                StringBuilder sb = new StringBuilder();
                IList<ExcelItem> excelItemList = excelData.ExcelItemList;
                ParentsGeneration parentGeneration = new ParentsGeneration();

                foreach (ExcelItem excelItem in excelItemList)
                {
                    if (excelItem.业务员 == "模板业务员") continue;
                    int autoIndex;string OrderCode = string.Empty; string OrderChildId = string.Empty;
                    if (excelItem.代次 == "父母代")
                    {
                        OrderCode = CPAutoNumHelper.Instance().GetNextAutoNum("OrderCode", out autoIndex);
                        OrderChildId = CPAutoNumHelper.Instance().GetNextAutoNum("OrderChildId", out autoIndex);
                    }
                    if (excelItem.代次 == "商品代")
                    {
                        OrderCode = CPAutoNumHelper.Instance().GetNextAutoNum("SPD_OrderCode", out autoIndex);
                        OrderChildId = CPAutoNumHelper.Instance().GetNextAutoNum("SPD_OrderChildId", out autoIndex);
                    }

                     string strSql = "";long total;long loadloss;
                    total = Convert.ToInt64(excelItem.公雏数量) + Convert.ToInt64(excelItem.母雏数量);
                    loadloss = Convert.ToInt64(excelItem.路耗数量);
                    DateTime WaitDeliveryTime = this.GetTime(excelItem.预计发货时间 == null ? 0 : Convert.ToInt64(excelItem.预计发货时间));
                    string UserId = CPExpressionHelper.Instance.RunCompile("${CPUser.UserId()}");
                    string UserName = CPExpressionHelper.Instance.RunCompile("${CPUser.UserName()}");
                    strSql = @"INSERT INTO dbo.YW_OrderInfo
                    (type,typeId,OrderCode,OrderStatus,Salesman,SalesmanTel,CustomerState,CustomerCity,CustomerDistrict,CustomerAddress,CustomerName,CustomerMobile,
                    OrgId,OrgName,SaleDeptId,SaleDeptName,title,TotalCount,OrderRoadLoss,WaitDeliveryTime,ZitiAddress,ZitiMemo,CancelStatus,AgentName,AgentTel,CreateUserID,CreateUserName)
                    VALUES('" + excelItem.代次 + "',1,'" + OrderCode + "','WAIT_BUYER_PAY','" + excelItem.业务员 + "','" + excelItem.业务员电话 + "','" + excelItem.省份 + "','" + excelItem.城市 + "'," +
                    "'" + excelItem.地区 + "','" + excelItem.地址 + "','" + excelItem.客户 + "','" + excelItem.客户电话 + "','" + parentGeneration.GetDeptIDByName(excelItem.公司名称) + "'," +
                    "'" + excelItem.公司名称 + "','" + parentGeneration.GetDeptIDByName(excelItem.销售部) + "','" + excelItem.销售部 + "','订单明细介绍'," + total + "," + loadloss + "," +
                    "'" + WaitDeliveryTime + "','" + excelItem.自提地址 + "','" + excelItem.自提备注 + "','NO_APPLY_CANCEL','" + excelItem.代理 + "','" + excelItem.代理电话 + "','" + UserId + "','" + UserName + "')";

                    parentGeneration.InsertYW_OrderInfo(strSql, grid);

                   
                    string VarietyId = string.Empty;string VarietyName = string.Empty;
                    if (excelItem.代次 == "父母代") { VarietyId = "405"; VarietyName = "父母代雏鸡"; }
                    if (excelItem.代次 == "商品代") { VarietyId = "404"; VarietyName = "商品代雏鸡"; }
                    long BuyChickCount = 0;
                    BuyChickCount = excelItem.母雏数量 == null ? 0 : Convert.ToInt64(excelItem.母雏数量);
                    long LossCount = 0;
                    LossCount = excelItem.路耗数量 == null ? 0 : Convert.ToInt64(excelItem.路耗数量);
                    long MaleBuyChickCount = 0;
                    MaleBuyChickCount = excelItem.公雏数量 == null ? 0 : Convert.ToInt64(excelItem.公雏数量);
                    long AdjustNumber = 0;
                    AdjustNumber = excelItem.调整数量 == null ? 0 : Convert.ToInt64(excelItem.调整数量);
                    string orderSql = @"INSERT INTO DBO.YW_OrderDetail
                                    (OrderId,OrderChildId,VarietyId,VarietyName,GoodsId,GoodsName,BuyChickCount,LossCount,MaleBuyChickCount,AdjustNumber,ValueAdded_Content)
                                    VALUES('" + OrderCode + "','" + OrderChildId + "','" + VarietyId + "','" + VarietyName + "'," +
                                    "'" + parentGeneration.GetCodeIdByCodeTitle(excelItem.品种, "405") + "','" + excelItem.品种 + "','" + BuyChickCount + "'," +
                                    "'" + LossCount + "','" + MaleBuyChickCount + "','" + AdjustNumber + "','" + excelItem.服务项目 + "')";

                    parentGeneration.InsertYW_OrderInfo(orderSql, grid);
                }
                re.Result = true;
                return re;
            }
            catch (Exception ex)
            {
                re.Result = false;
                _logger.Error(string.Format("【订单数据导入excel】发生异常异常信息为{0}", ex.Message));
                re.ErrorMsg = ex.Message.ToString();
                return re;
            }
        }

        #region 私有方法
        /// 天为C#格式时间
        /// </summary>
        /// <param name=”timeStamp”></param>
        /// <returns></returns>
        private DateTime GetTime(long timeStamp)
        {
           // DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1899, 12, 30));

            DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
            dtFormat.ShortDatePattern = "yyyy-MM-dd";
            DateTime dtStart = Convert.ToDateTime("1899-12-30", dtFormat);
            return dtStart.AddDays(timeStamp);
        }
        #endregion
    }

    public class ExcelData {
        public int CurUserId { get; set; }
        public string CurUserIden { get; set; }
        public string GridCode { get; set; }
        public IList<ExcelItem> ExcelItemList { get; set; }
    }

    public class ExcelItem {
        public string 代次 { get; set; }
        public string 公司名称 { get; set; }
        public string 销售部 { get; set; }
        public string 业务员 { get; set; }
        public string 业务员电话 { get; set; }
        public string 省份 { get; set; }
        public string 城市 { get; set; }
        public string 地区 { get; set; }
        public string 地址 { get; set; }
        public string 客户 { get; set; }
        public string 客户电话 { get; set; }
        //public string 进雏总数量 { get; set; }
        //public string 路耗总数量 { get; set; }
        public string 预计发货时间 { get; set; }
        public string 自提地址 { get; set; }
        public string 自提备注 { get; set; }
        public string 商品类目 { get; set; }
        public string 品种 { get; set; }
        public string 母雏数量 { get; set; }
        public string 路耗数量 { get; set; }
        public string 调整数量 { get; set; }
        public string 公雏数量 { get; set; }

        public string 代理 { get; set; }
        public string 代理电话 { get; set; }
        public string 服务项目 { get; set; }

    }
}
